//1. 导入 express
const express = require('express');
//2. 创建路由对象
const router = express.Router();

//导入 moment
const moment = require('moment');
const AccountModel = require('../../models/AccountModel');

//声明中间件
let checkLogin = (req, res, next) => {
  if (!req.session.username){
    return res.redirect('/login');
  }
  next();
}

//3. 创建路由规则
//首页
router.get('/', checkLogin,(req, res) => {
  res.redirect('/account');
});

//记账本的列表
router.get('/account', checkLogin,(req, res) => {
  AccountModel.find().sort({ time: -1 }).exec().then(data => {
    res.render('list', { accounts: data, moment: moment,username: req.session.username });
  }).catch(err => {
    res.status(500).send('数据库读取失败~~~');
  });
});

//添加记录
router.get('/account/create', checkLogin,(req, res) => {
  // res.send('添加账单');
  res.render('create');
});
//新增记录
router.post('/account', checkLogin,async (req, res) => {
  try {
    const data = await AccountModel.create({
      ...req.body,
      time: moment(req.body.time).toDate()
    });
    res.render('success', { msg: '添加成功哦\~~\~', url: '/account' });
  } catch (err) {
    res.status(500).send('插入失败\~\~');
  }
});

//删除记录
router.get('/account/:id', checkLogin,(req, res) => {
  AccountModel.deleteOne({ _id: req.params.id }).then(data => {
    res.render('success', { msg: '删除成功~~~', url: '/account' });
  }).catch(err => {
    res.status(500).send('删除失败~');
  });
});

//4. 暴露 router
module.exports = router;
